package org.example.my_netty;


import lombok.Getter;
import org.example.my_netty.myNettyHandlerChain.MyHandlerChain;
import org.example.my_netty.myNettyHandlerChain.MyNettyHandler;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//每个worker的上下文信息 目的是为了让他能感知外部（大局）情况
public class MyNettyContext {

    //根据不同的worker 存不同的小channel的数据上下文
    private final Map<SocketChannel,SocketChannelContext>  socketChannelContextMap=new ConcurrentHashMap<>();


    //方法链是公共的 但是数据不是公共的 是和channel绑定的
    @Getter
    //过滤器链
    private final MyHandlerChain myHandlerChain =new MyHandlerChain();



    //获得小channel的数据上下文 线程安全的 懒加载
    public SocketChannelContext getSocketChannelContext(SocketChannel socketChannel){
        return socketChannelContextMap.computeIfAbsent(socketChannel,socketChannel1 -> new SocketChannelContext());
    }



    public void addHandler(MyNettyHandler handler) {
        myHandlerChain.addHandler(handler);
    }

    //上下文处理读事件 实际上是通过链去处理
    public void handle(SocketChannel channel) throws Exception {
        SocketChannelContext socketChannelContext = getSocketChannelContext(channel);
        myHandlerChain.handle(channel, socketChannelContext);
    }
}
